<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'

import {
    useMessage,
    NButton, NForm, NFormItem, NInput, NInputNumber, NPopconfirm, NTreeSelect, NTag, NSwitch, NFlex,
    NAvatar, NSelect, NImage
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import TheIcon from '@/components/icon/TheIcon.vue'
import { getToken } from '@/utils'
import { renderIcon } from '@/utils'
import { useCRUD } from '@/composables'
// import { loginTypeMap, loginTypeOptions } from '@/constant/data'
import api from '@/api'

defineOptions({ name: '品牌管理' })

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const base_path = import.meta.env.VITE_BASE

const {
    modalVisible,
    modalTitle,
    modalLoading,
    handleSave,
    modalForm,
    modalFormRef,
    handleEdit,
    handleDelete,
    handleAdd,
} = useCRUD({
    name: '品牌',
    initForm: {},
    doCreate: api.creategoodsBrand,
    doUpdate: api.updategoodsBrand,
    doDelete: api.deletegoodsBrand,
    refresh: () => $table.value?.handlerefresh(),
})
const isDisabled = ref(false)
const data = reactive({
    attributeOption: [{
        id: 1,
        name: '描述品牌'
    },
    {
        id: 2,
        name: '规格品牌'
    },
    ],
    uploadAction: base_path + 'api/goods/brand/file',
    token: getToken(),
});


onMounted(() => {
    $table.value?.handleSearch()
    // api.getCategory().then((res) => (deptOption.value = res.data))
    //   api.getgoodsCategoryTree().then((res) => (deptOption.value = res.data))
})
//封面图
const message = useMessage();
const customRequestMethod1 = (options) => {
    console.log(options, 'options');

    const { file } = options.file;
    const formData = new FormData();
    formData.append('file', file);
    fetch(data.uploadAction, {
        method: 'POST',
        headers: options.headers,
        body: formData,
    })
        .then((response) => response.json())
        .then((data) => {
            console.log(data, 'datatat');
            if (data.code == 200) {
                modalForm.value.logo_image = data.data.url
                message.success('封面图上传成功');
                options.onProgress(data);
            } else {
                message.error(data.msg);
            }
        })
}
const customRequestMethod2 = (options) => {
    console.log(options, 'options');

    const { file } = options.file;
    const formData = new FormData();
    formData.append('file', file);
    fetch(data.uploadAction, {
        method: 'POST',
        headers: options.headers,
        body: formData,
    })
        .then((response) => response.json())
        .then((data) => {
            console.log(data, 'datatat');
            if (data.code == 200) {
                modalForm.value.share_image = data.data.url
                message.success('封面图上传成功');
                options.onProgress(data);
            } else {
                message.error(data.msg);
            }
        })
}
const customRequestMethod3 = (options) => {
    console.log(options, 'options');
    const { file } = options.file;
    const formData = new FormData();
    formData.append('file', file);
    fetch(data.uploadAction, {
        method: 'POST',
        headers: options.headers,
        body: formData,
    })
        .then((response) => response.json())
        .then((data) => {
            console.log(data, 'datatat');
            if (data.code == 200) {
                modalForm.value.cover = data.data.url
                message.success('封面图上传成功');
                options.onProgress(data);
            } else {
                message.error(data.msg);
            }
        })
}

async function addDepts() {
    isDisabled.value = false
    handleAdd()
}

const columns = [
    {
        title: 'ID',
        key: 'id',
        width: 40,
        align: 'center',
        ellipsis: { tooltip: true },
    },
    {
        title: '品牌名',
        key: 'name',
        width: 'auto',
        align: 'center',
        ellipsis: { tooltip: true },
        fixed: 'left',
    },
    {
        title: '品牌英文名',
        key: 'name_english',
        width: 'auto',
        align: 'center',
        ellipsis: { tooltip: true },
    },
    {
        title: 'Logo',
        key: 'logo_image',
        width: '100',
        align: 'center',
        ellipsis: { tooltip: true },
        render(row) {
            let img_src = row.logo_image
            return h(NFlex, {},
                [h(NAvatar, {
                    src: img_src,
                    size: "small",
                })]
            )

        },
    },
    {
        title: '分享图',
        key: 'share_image',
        width: '100',
        align: 'center',
        ellipsis: { tooltip: true },
        render(row) {
            let img_src = row.share_image
            return h(NFlex, {},
                [h(NAvatar, {
                    src: img_src,
                    size: "small",
                })]
            )

        },
    },
    {
        title: '封面',
        key: 'cover',
        width: '100',
        align: 'center',
        ellipsis: { tooltip: true },
        render(row) {
            let img_src =  row.cover
            return h(NFlex, {},
                [h(NAvatar, {
                    src: img_src,
                    size: "small",
                })]
            )

        },
    },
    // {
    //     title: '品牌类型',
    //     key: 'topic_id',
    //     width: 100,
    //     align: 'center',

    // },
    {
        title: '创建时间',
        key: 'created_at',
        align: 'center',
        width: 'auto',
        ellipsis: { tooltip: true },
    },
    {
        title: '操作',
        key: 'actions',
        width: 'auto',
        align: 'center',
        fixed: 'right',
        render(row) {
            return [
                withDirectives(
                    h(
                        NButton,
                        {
                            size: 'small',
                            type: 'primary',
                            style: 'margin-right: 8px;',
                            onClick: () => {
                                console.log('row', row.parent_id)
                                if (row.parent_id === 0) {
                                    isDisabled.value = true
                                } else {
                                    isDisabled.value = false
                                }
                                handleEdit(row)
                            },
                        },
                        {
                            default: () => '编辑',
                            icon: renderIcon('material-symbols:edit', { size: 16 }),
                        }
                    ),
                    [[vPermission, 'post/api/content/category/update']]
                ),
                h(
                    NPopconfirm,
                    {
                        onPositiveClick: () => handleDelete({ data_id: row.id }, false),
                        onNegativeClick: () => { },
                    },
                    {
                        trigger: () =>
                            withDirectives(
                                h(
                                    NButton,
                                    {
                                        size: 'small',
                                        type: 'error',
                                    },
                                    {
                                        default: () => '删除',
                                        icon: renderIcon('material-symbols:delete-outline', { size: 16 }),
                                    }
                                ),
                                [[vPermission, 'delete/api/content/category/delete']]
                            ),
                        default: () => h('div', {}, '确定删除该分类吗?'),
                    }
                ),
            ]
        },
    },
]
const validateAddUser = {
    name: [
        {
            required: true,
            message: '请输入品牌名称',
            trigger: ['input', 'blur', 'change'],
        },
    ],
}
</script>

<template>
    <!-- 业务页面 -->
    <CommonPage show-footer title="品牌管理列表">
        <template #action>
            <div>
                <NButton v-permission="'post/api/content/category/create'" class="float-right mr-15" type="primary"
                    @click="addDepts">
                    <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />新建品牌
                </NButton>
            </div>
        </template>
        <!-- 表格 -->
        <CrudTable ref="$table" v-model:query-items="queryItems" :columns="columns" :get-data="api.getgoodsBrand"
        :scroll-x="1100">
            <template #queryBar>
                <QueryBarItem label="品牌名称" :label-width="80">
                    <NInput v-model:value="queryItems.name" clearable type="text" placeholder="请输入品牌名称"
                        @keypress.enter="$table?.handleSearch()" />
                </QueryBarItem>
            </template>
        </CrudTable>

        <!-- 新增/编辑 弹窗 -->
        <CrudModal v-model:visible="modalVisible" :title="modalTitle" :loading="modalLoading" @save="handleSave"
            style="width: 750px !important;">
            <NForm ref="modalFormRef" label-placement="left" label-align="left" :label-width="80" :model="modalForm"
                :rules="validateAddUser">
                <NFlex justify="space-between">
                    <NFormItem label="品牌名称" path="name" style="width: 100%;">
                        <NInput v-model:value="modalForm.name" clearable placeholder="请输入品牌名称" />
                    </NFormItem>
                    <NFormItem label="英文名" path="name_english" style="width: 100%;">
                        <NInput v-model:value="modalForm.name_english" clearable placeholder="请输入品牌英文名" />
                    </NFormItem>
                    <NFormItem label="品牌介绍" path="desc">
                        <NInput style="width: 590px;" type="textarea" v-model:value="modalForm.desc" clearable
                            placeholder="请填写品牌介绍" />
                    </NFormItem>
                    <NFormItem label="品牌Logo" path="logo_image" style="width:100%">
                        <NImage v-if="modalForm.logo_image" width="60" style="border-radius: 5px;margin-right: 15px;"
                            :src="modalForm.logo_image"></NImage>
                        <NUpload :action="data.uploadAction" :headers="{ token: data.token }" :max="1"
                            :show-file-list=false :custom-request="customRequestMethod1" list-type="image">
                            <NButton>上传</NButton>
                        </NUpload>
                    </NFormItem>
                    <NFormItem label="分享图" path="share_image" style="width:100%">
                        <NImage v-if="modalForm.share_image" width="60" style="border-radius: 5px;margin-right: 15px;"
                            :src="modalForm.share_image"></NImage>
                        <NUpload :action="data.uploadAction" :headers="{ token: data.token }" :max="1"
                            :show-file-list=false :custom-request="customRequestMethod2" list-type="image">
                            <NButton>上传</NButton>
                        </NUpload>
                    </NFormItem>
                    <NFormItem label="封面图" path="cover" style="width:100%">
                        <NImage v-if="modalForm.cover" width="60" style="border-radius: 5px;margin-right: 15px;"
                            :src="modalForm.cover"></NImage>
                        <NUpload :action="data.uploadAction" :headers="{ token: data.token }" :max="1"
                            :show-file-list=false :custom-request="customRequestMethod3" list-type="image">
                            <NButton>上传</NButton>
                        </NUpload>
                    </NFormItem>
                </NFlex>
            </NForm>
        </CrudModal>
    </CommonPage>
</template>
